<template>
  <view class="city-select">
    <!-- 顶部导航标签 -->
    <view class="tabs-container">
      <view class="tab active">国内(含港澳台)</view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="back-btn" @click="onCancel">
        <text>×</text>
      </view>
      <view class="search-box">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          placeholder="搜索城市/区县" 
          v-model="searchKeyword"
          @input="debounceSearch"
        />
        <text v-if="searchKeyword" class="clear-icon" @click="clearSearch">×</text>
      </view>
    </view>

    <scroll-view 
      scroll-y 
      class="cities-container" 
      :scroll-into-view="currentLetter ? 'letter-' + currentLetter : ''"
      :style="{ height: scrollViewHeight + 'px' }"
    >
      <!-- 搜索结果 -->
      <view v-if="searchKeyword && searchResults.length > 0" class="search-results">
        <!-- 搜索结果分组 -->
        <view v-if="groupedResults.province.length > 0" class="result-group">
          <view class="group-title">省份</view>
          <view 
            v-for="(city, index) in groupedResults.province" 
            :key="'province-'+index"
            class="search-result-item province-item"
            @click="onSelectCity(city)"
          >
            <rich-text :nodes="highlightKeyword(city.name, searchKeyword)"></rich-text>
          </view>
        </view>
        
        <view v-if="groupedResults.city.length > 0" class="result-group">
          <view class="group-title">城市</view>
          <view 
            v-for="(city, index) in groupedResults.city" 
            :key="'city-'+index"
            class="search-result-item city-item"
            @click="onSelectCity(city)"
          >
            <rich-text :nodes="highlightKeyword(city.name, searchKeyword)"></rich-text>
            <text v-if="city.province" class="province-text">,{{ city.province }}</text>
          </view>
        </view>
        
        <view v-if="groupedResults.district.length > 0" class="result-group">
          <view class="group-title">区县</view>
          <view 
            v-for="(city, index) in groupedResults.district" 
            :key="'district-'+index"
            class="search-result-item district-item"
            @click="onSelectCity(city)"
          >
            <rich-text :nodes="highlightKeyword(city.name, searchKeyword)"></rich-text>
            <text v-if="city.province" class="province-text">,{{ city.province }}</text>
          </view>
        </view>
      </view>

      <!-- 无搜索结果提示 -->
      <view v-if="searchKeyword && searchResults.length === 0 && !loading" class="no-results">
        <text class="no-results-text">未找到相关城市</text>
        <text class="search-tip">请尝试搜索城市名称，如"南昌"、"北京"</text>
      </view>

      <!-- 非搜索状态下显示的内容 -->
      <block v-if="!searchKeyword">
        <!-- 定位/历史访问城市 -->
        <view class="section" id="history-section">
          <view class="section-title">定位/历史访问城市</view>
          <view class="history-cities">
            <view class="history-city" @click="onSelectCity(currentCity)">
              <text class="location-icon">📍</text>
              <text class="city-name">{{ currentCity.city }}</text>
            </view>
            <view 
              v-for="(city, index) in historyCities" 
              :key="index"
              class="history-city"
              @click="onSelectCity(city)"
            >
              {{ city.name }}
            </view>
          </view>
        </view>

        <!-- 所选城市的相关区县 -->
        <view v-if="relatedDistricts.length > 0" class="section">
          <view class="section-title">所选{{ currentCity.city }}的相关市/区/县</view>
          <view class="related-districts">
            <view 
              v-for="(district, index) in relatedDistricts" 
              :key="index"
              class="district-item"
              @click="onSelectCity(district)"
            >
              {{ district.name }}
            </view>
          </view>
        </view>

        <!-- 国内热门城市 -->
        <view class="section" id="hot-section">
          <view class="section-title">国内热门城市</view>
          <view class="hot-cities">
            <view 
              v-for="(city, index) in hotCities" 
              :key="index"
              class="hot-city"
              @click="onSelectCity(city)"
            >
              {{ city.name }}
            </view>
          </view>
        </view>

        <!-- 按字母排序的城市列表 -->
        <view v-for="letter in alphabet" :key="letter" class="letter-section" :id="`letter-${letter}`">
          <view class="letter-title">{{ letter }}</view>
          <view class="letter-cities">
            <view 
              v-for="(city, idx) in citiesByLetter[letter] || []" 
              :key="idx"
              class="city-item"
              @click="onSelectCity(city)"
            >
              {{ city.name }}
            </view>
          </view>
        </view>
      </block>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">正在加载城市列表...</text>
      </view>
      
      <!-- 错误状态 -->
      <view v-if="error" class="error-state">
        <text class="error-text">{{ error }}</text>
        <view class="retry-btn" @click="loadCityData">重试</view>
      </view>
    </scroll-view>

    <!-- 字母索引栏 (仅在非搜索状态显示) -->
    <view v-if="!searchKeyword" class="alphabet-index">
      <text 
        v-for="letter in alphabet" 
        :key="letter"
        class="letter"
        :class="{ active: currentLetter === letter }"
        @click="scrollToLetter(letter)"
      >
        {{ letter }}
      </text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { getDistrict, getIpLocation } from '../../api/GaoDeApi';
import { getLastLocation, saveLastLocation } from '../../api/location';

// 获取页面参数
const sourcePages = ref('');
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.options) {
    sourcePages.value = currentPage.options.source || '';
    console.log('来源页面:', sourcePages.value);
  }
});

// 状态变量
const loading = ref(false);
const error = ref('');
const searchKeyword = ref('');
const searchResults = ref([]);
const scrollViewHeight = ref(600); // 默认高度，后续会动态计算
let searchTimer = null; // 用于防抖的定时器

// 当前选中的字母
const currentLetter = ref('');

// 字母表
const alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

// 按字母分组的城市
const citiesByLetter = reactive({});

// 当前定位城市
const currentCity = ref({
  city: '进贤县',
  adcode: '360124',
  isActive: false
});

// 历史访问城市
const historyCities = ref([
  { name: '南昌', adcode: '360100', isActive: false },
  { name: '杭州', adcode: '330100', isActive: false },
  { name: '长沙', adcode: '430100', isActive: false },
]);

// 相关区县
const relatedDistricts = ref([
  { name: '南昌县', adcode: '360121', isActive: false },
  { name: '安义县', adcode: '360123', isActive: false },
  { name: '南昌县', adcode: '360121', isActive: false },
]);

// 热门城市列表
const hotCities = ref([
  { name: '上海', adcode: '310000', isActive: false },
  { name: '北京', adcode: '110000', isActive: false },
  { name: '广州', adcode: '440100', isActive: false },
  { name: '杭州', adcode: '330100', isActive: true },
  { name: '成都', adcode: '510100', isActive: false },
  { name: '深圳', adcode: '440300', isActive: false },
  { name: '苏州', adcode: '320500', isActive: false },
  { name: '南京', adcode: '320100', isActive: false },
  { name: '天津', adcode: '120000', isActive: false },
  { name: '重庆', adcode: '500000', isActive: false },
  { name: '西安', adcode: '610100', isActive: false },
  { name: '长沙', adcode: '430100', isActive: false },
  { name: '武汉', adcode: '420100', isActive: true },
  { name: '厦门', adcode: '350200', isActive: false },
  { name: '无锡', adcode: '320200', isActive: false },
  { name: '三亚', adcode: '460200', isActive: false },
]);

// 清除搜索内容
const clearSearch = () => {
  searchKeyword.value = '';
  searchResults.value = [];
};

// 带防抖功能的搜索函数
const debounceSearch = (event) => {
  // 清除之前的定时器
  if (searchTimer) clearTimeout(searchTimer);
  
  // 设置新的定时器，延迟500ms执行搜索
  searchTimer = setTimeout(() => {
    onSearchInput();
  }, 500);
};

// 高亮搜索关键词
const highlightKeyword = (text, keyword) => {
  if (!keyword || !text) return text;
  
  try {
    // 使用更安全的方式创建高亮HTML
    const parts = text.split(new RegExp(`(${keyword})`, 'i'));
    let result = '';
    
    parts.forEach(part => {
      if (part.toLowerCase() === keyword.toLowerCase()) {
        // 高亮匹配部分
        result += `<span style="color: #ff7f00;">${part}</span>`;
      } else {
        // 保持其他部分不变
        result += part;
      }
    });
    
    return result;
  } catch (err) {
    console.error('高亮关键词出错:', err);
    return text; // 出错时返回原文本
  }
};

// 搜索城市
const onSearchInput = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = [];
    return;
  }
  
  loading.value = true;
  
  try {
    const res = await getDistrict({
      keywords: searchKeyword.value,
      subdistrict: 2,  // 获取下两级行政区，以确保能获取到省份下的城市和区县
      extensions: 'base'
    });
    if (res.data && res.data.status === '1' && res.data.districts && res.data.districts.length > 0) {
      const results = [];
      
      // 处理搜索结果，添加省份信息
      res.data.districts.forEach(district => {
        // 如果是省级
        if (district.level === 'province') {
          // 添加省本身
          if (district.name.includes(searchKeyword.value)) {
            results.push({
              name: district.name,
              adcode: district.adcode,
              citycode: district.citycode || '',
              level: district.level,
              province: '',  // 省级没有上级省份
              isActive: false
            });
          }
          
          // 无论省名是否包含关键词，都添加该省下的所有城市
          if (district.districts && district.districts.length > 0) {
            district.districts.forEach(city => {
              // 添加所有城市，不仅仅是名称包含关键词的
              results.push({
                name: city.name,
                adcode: city.adcode,
                citycode: city.citycode || '',
                level: city.level,
                province: district.name,  // 添加省份信息
                isActive: false
              });
              
              // 如果是搜索省份的情况，也可以添加热门区县
              if (district.name.includes(searchKeyword.value) && city.districts && city.districts.length > 0) {
                // 只添加前几个区县，避免结果过多
                const counties = city.districts.slice(0, 3);
                counties.forEach(county => {
                  results.push({
                    name: county.name,
                    adcode: county.adcode,
                    citycode: county.citycode || '',
                    level: county.level,
                    province: `${city.name}`,  // 只显示城市名称，避免显示太长
                    isActive: false
                  });
                });
              }
            });
          }
        } 
        // 如果是市级
        else if (district.level === 'city') {
          // 添加城市本身
          results.push({
            name: district.name,
            adcode: district.adcode,
            citycode: district.citycode || '',
            level: district.level,
            province: '',  // 可能需要额外请求获取上级省份
            isActive: false
          });
          
          // 添加该市下的所有区县
          if (district.districts && district.districts.length > 0) {
            district.districts.forEach(county => {
              results.push({
                name: county.name,
                adcode: county.adcode,
                citycode: county.citycode || '',
                level: county.level,
                province: district.name,  // 市级作为"省份"显示
                isActive: false
              });
            });
          }
        }
        // 如果直接是区县级
        else if (district.level === 'district') {
          results.push({
            name: district.name,
            adcode: district.adcode,
            citycode: district.citycode || '',
            level: district.level,
            province: '',  // 可能需要额外请求获取上级城市
            isActive: false
          });
        }
      });
      
      // 对结果进行排序：省份在前，城市在中，区县在后
      results.sort((a, b) => {
        const levelOrder = { province: 1, city: 2, district: 3 };
        return levelOrder[a.level] - levelOrder[b.level];
      });
      
      // 更新搜索结果
      searchResults.value = results;
    } else {
      // 如果API没有返回结果，尝试从已加载的城市中搜索
      const results = [];
      
      // 搜索已加载的城市数据
      alphabet.forEach(letter => {
        if (citiesByLetter[letter] && citiesByLetter[letter].length > 0) {
          const matches = citiesByLetter[letter].filter(city => 
            city.name.includes(searchKeyword.value)
          );
          results.push(...matches);
        }
      });
      
      searchResults.value = results;
    }
  } catch (err) {
    console.error('搜索城市出错:', err);
    searchResults.value = [];
    
    // 从已加载的城市中搜索
    const results = [];
    alphabet.forEach(letter => {
      if (citiesByLetter[letter] && citiesByLetter[letter].length > 0) {
        const matches = citiesByLetter[letter].filter(city => 
          city.name.includes(searchKeyword.value)
        );
        results.push(...matches);
      }
    });
    searchResults.value = results;
  } finally {
    loading.value = false;
  }
};

// 取消选择
const onCancel = () => {
  try {
    // 获取当前页面栈
    const pages = getCurrentPages();
    
    if (pages.length > 1) {
      // 如果有上一页，则返回上一页
      uni.navigateBack({
        fail: (err) => {
          console.error('返回上一页失败:', err);
          // 返回失败时，尝试跳转到首页
          navigateToHome();
        }
      });
    } else {
      // 如果已经是第一页，则跳转到首页
      navigateToHome();
    }
  } catch (err) {
    console.error('页面导航错误:', err);
    // 发生错误时，尝试跳转到首页
    navigateToHome();
  }
};

// 跳转到首页
const navigateToHome = () => {
  // 根据实际情况修改首页路径
  uni.switchTab({
    url: '/pages/discovery/index',
    fail: (err) => {
      console.error('跳转到首页失败:', err);
      // 如果switchTab失败，尝试使用reLaunch
      uni.reLaunch({
        url: '/pages/discovery/index'
      });
    }
  });
};

// 选择城市
const onSelectCity = (city) => {
  // 构造标准的城市对象
  let selectedCity = {};
  
  // 根据不同来源页面返回不同格式数据
  if (sourcePages.value === 'AI-travel') {
    // AI-travel.vue 页面需要的格式
    selectedCity = {
      adcode: city.adcode,
      city: city.name || city.city,
      name: city.name || city.city
    };
  } else if (sourcePages.value === 'weather') {
    // weather.vue 页面需要的格式
    selectedCity = {
      adcode: city.adcode,
      cityName: city.name || city.city,
    };
  } else {
    // 默认格式
    selectedCity = {
      adcode: city.adcode,
      city: city.name || city.city,
      name: city.name || city.city
    };
  }
  
  const userInfo = uni.getStorageSync('userInfo');
  saveLastLocation({userId:userInfo.id,city:selectedCity.city || selectedCity.name || selectedCity.cityName,adcode:selectedCity.adcode});
  
  // 触发选择城市事件
  uni.$emit('city-selected-' + (sourcePages.value || 'default'), selectedCity);
  
  // 添加延迟，确保事件处理完成后再关闭页面
  setTimeout(() => {
    onCancel();
  }, 100);
};

// 获取当前位置
const getCurrentLocation = async () => {
  try {
    const res = await getIpLocation();
    
    if (res && res.data) {
      currentCity.value = {
        city: res.data.city || '未知城市',
        adcode: res.data.adcode || '',
        isActive: false
      };
      
      // 获取当前城市相关的区县
      if (currentCity.value && currentCity.value.adcode) {
        await loadRelatedDistricts(currentCity.value.adcode);
      }
    }
  } catch (err) {
    console.error('获取当前位置出错:', err);
    currentCity.value = {
      city: '北京市',
      adcode: '110000',
      isActive: false
    };
  }
};

// 获取相关区县
const loadRelatedDistricts = async (adcode) => {
  if (!adcode) return;
  
  try {
    const res = await getDistrict({
      keywords: adcode,
      subdistrict: 1,
      extensions: 'base'
    });
    
    
    if (res.data && res.data.status === '1' && res.data.districts && res.data.districts.length > 0) {
      const districts = res.data.districts[0].districts || [];
      
      // 排除自身，只保留下级区域
      const filteredDistricts = districts.filter(item => 
        item.adcode !== adcode && item.level === 'district'
      );
      
      relatedDistricts.value = filteredDistricts.map(item => ({
        name: item.name,
        adcode: item.adcode,
        citycode: item.citycode || '',
        level: item.level,
        isActive: false
      }));
      
    } else {
      relatedDistricts.value = [];
    }
  } catch (err) {
    console.error('获取相关区县出错:', err);
    relatedDistricts.value = [];
  }
};

// 设置滚动区域高度
const setScrollViewHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  scrollViewHeight.value = systemInfo.windowHeight - 100; // 减去头部和底部的高度
};

// 跳转到指定字母区域
const scrollToLetter = (letter) => {
  currentLetter.value = letter;
  
  // 检查该字母是否有城市数据
  if (citiesByLetter[letter] && citiesByLetter[letter].length > 0) {
    // 使用nextTick确保DOM更新后再滚动
    nextTick(() => {
      const el = document.getElementById(`letter-${letter}`);
      if (el) {
        const scrollView = document.querySelector('.cities-container');
        if (scrollView) {
          scrollView.scrollTop = el.offsetTop;
        }
      }
    });
  }
};

// 加载城市数据
const loadCityData = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 获取中国城市数据
    const res = await getDistrict({
      keywords: '中国',
      subdistrict: 3,  // 获取到区县级别
      extensions: 'base'
    });
    
    
    if (res.data && res.data.status === '1' && res.data.districts && res.data.districts.length > 0) {
      // 成功获取数据，处理城市列表
      processDistrictsData(res.data.districts);
    } else {
      console.error('获取城市数据失败:', res);
      error.value = '获取城市数据失败，请稍后重试';
      
      // 使用静态数据作为备用
      useFallbackCityData();
    }
  } catch (err) {
    console.error('获取城市数据出错:', err);
    error.value = '获取城市数据出错，请稍后重试';
    
    // 使用静态数据作为备用
    useFallbackCityData();
  } finally {
    loading.value = false;
  }
};

// 使用备用城市数据（当API请求失败时）
const useFallbackCityData = () => {
  // 主要城市的静态数据
  const staticCities = [
    { name: '北京', adcode: '110000', letter: 'B' },
    { name: '上海', adcode: '310000', letter: 'S' },
    { name: '广州', adcode: '440100', letter: 'G' },
    { name: '深圳', adcode: '440300', letter: 'S' },
    { name: '南京', adcode: '320100', letter: 'N' },
    { name: '杭州', adcode: '330100', letter: 'H' },
    { name: '成都', adcode: '510100', letter: 'C' },
    { name: '重庆', adcode: '500000', letter: 'C' },
    { name: '武汉', adcode: '420100', letter: 'W' },
    { name: '西安', adcode: '610100', letter: 'X' },
    { name: '长沙', adcode: '430100', letter: 'C' },
    { name: '天津', adcode: '120000', letter: 'T' },
    { name: '苏州', adcode: '320500', letter: 'S' },
    { name: '青岛', adcode: '370200', letter: 'Q' },
    { name: '厦门', adcode: '350200', letter: 'X' },
    { name: '郑州', adcode: '410100', letter: 'Z' },
    { name: '大连', adcode: '210200', letter: 'D' },
    { name: '宁波', adcode: '330200', letter: 'N' },
    { name: '济南', adcode: '370100', letter: 'J' },
    { name: '哈尔滨', adcode: '230100', letter: 'H' },
    { name: '沈阳', adcode: '210100', letter: 'S' },
    { name: '无锡', adcode: '320200', letter: 'W' },
    { name: '福州', adcode: '350100', letter: 'F' },
    { name: '太原', adcode: '140100', letter: 'T' },
    { name: '长春', adcode: '220100', letter: 'C' },
    { name: '石家庄', adcode: '130100', letter: 'S' },
    { name: '南昌', adcode: '360100', letter: 'N' },
    { name: '昆明', adcode: '530100', letter: 'K' }
  ];
  
  // 清空现有数据
  alphabet.forEach(letter => {
    citiesByLetter[letter] = [];
  });
  
  // 按照首字母分组
  staticCities.forEach(city => {
    if (alphabet.includes(city.letter)) {
      citiesByLetter[city.letter].push({
        name: city.name,
        adcode: city.adcode,
        citycode: '',
        level: 'city',
        isActive: false
      });
    }
  });
  
  // 对每个字母下的城市进行排序
  alphabet.forEach(letter => {
    if (citiesByLetter[letter] && citiesByLetter[letter].length > 0) {
      citiesByLetter[letter].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
    }
  });
};

// 处理城市数据，按首字母分组
const processDistrictsData = (districts) => {
  // 清空现有数据
  alphabet.forEach(letter => {
    citiesByLetter[letter] = [];
  });
  
  // 递归提取所有城市
  const extractCities = (districts) => {
    if (!districts || !districts.length) return;
    
    districts.forEach(district => {
      // 处理省级、市级和区县级
      if (district.level === 'city' || district.level === 'district' || district.level === 'province') {
        const letter = getFirstLetter(district.name);
        
        if (alphabet.includes(letter)) {
          // 检查是否已存在相同名称的城市，避免重复
          const exists = citiesByLetter[letter].some(city => city.name === district.name);
          if (!exists) {
            citiesByLetter[letter].push({
              name: district.name,
              adcode: district.adcode,
              citycode: district.citycode || '',
              level: district.level,
              isActive: false
            });
          }
        }
      }
      
      // 如果有子区域，继续提取
      if (district.districts && district.districts.length > 0) {
        extractCities(district.districts);
      }
    });
  };
  
  extractCities(districts);
  
  // 对每个字母下的城市进行排序
  alphabet.forEach(letter => {
    if (citiesByLetter[letter] && citiesByLetter[letter].length > 0) {
      citiesByLetter[letter].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
    }
  });
};

// 获取汉字的拼音首字母（增强版）
const getFirstLetter = (name) => {
  if (!name) return '#';
  
  // 简单处理：这里仅作示例
  const firstChar = name.charAt(0);
  
  // 更完整的特殊城市名称映射
  const specialCityMap = {
    '阿': 'A', '安': 'A', '鞍': 'A',
    '北': 'B', '保': 'B', '宝': 'B', '包': 'B', '巴': 'B', '白': 'B',
    '成': 'C', '重': 'C', '长': 'C', '常': 'C', '潮': 'C', '郴': 'C', '池': 'C', '赤': 'C',
    '大': 'D', '德': 'D', '东': 'D', '丹': 'D', '达': 'D', '定': 'D',
    '鄂': 'E',
    '福': 'F', '佛': 'F', '防': 'F', '抚': 'F', '阜': 'F',
    '广': 'G', '贵': 'G', '桂': 'G', '赣': 'G', '甘': 'G', '高': 'G',
    '杭': 'H', '湖': 'H', '合': 'H', '哈': 'H', '海': 'H', '邯': 'H', '衡': 'H', '黄': 'H', '呼': 'H', '惠': 'H', '淮': 'H', '黑': 'H',
    '济': 'J', '嘉': 'J', '江': 'J', '金': 'J', '吉': 'J', '荆': 'J', '景': 'J', '揭': 'J', '晋': 'J', '佳': 'J',
    '昆': 'K', '开': 'K',
    '兰': 'L', '廊': 'L', '丽': 'L', '连': 'L', '辽': 'L', '聊': 'L', '临': 'L', '柳': 'L', '洛': 'L', '泸': 'L', '拉': 'L',
    '马': 'M', '茂': 'M', '梅': 'M', '眉': 'M', '绵': 'M', '牡': 'M',
    '南': 'N', '宁': 'N',
    '盘': 'P', '莆': 'P', '濮': 'P', '平': 'P',
    '青': 'Q', '秦': 'Q', '泉': 'Q', '清': 'Q', '七': 'Q', '齐': 'Q',
    '日': 'R',
    '上': 'S', '深': 'S', '苏': 'S', '沈': 'S', '石': 'S', '汕': 'S', '三': 'S', '遂': 'S', '松': 'S', '山': 'S', '绍': 'S', '十': 'S', '随': 'S', '邵': 'S', '韶': 'S', '宿': 'S',
    '天': 'T', '台': 'T', '唐': 'T', '太': 'T', '泰': 'T', '铜': 'T', '通': 'T',
    '无': 'W', '乌': 'W', '武': 'W', '温': 'W', '芜': 'W', '梧': 'W', '潍': 'W', '威': 'W',
    '厦': 'X', '西': 'X', '襄': 'X', '徐': 'X', '新': 'X', '咸': 'X', '信': 'X', '湘': 'X', '许': 'X', '孝': 'X', '忻': 'X', '仙': 'X',
    '烟': 'Y', '银': 'Y', '宜': 'Y', '岳': 'Y', '阳': 'Y', '玉': 'Y', '云': 'Y', '盐': 'Y', '扬': 'Y', '延': 'Y', '鹰': 'Y', '营': 'Y', '永': 'Y',
    '郑': 'Z', '株': 'Z', '珠': 'Z', '张': 'Z', '湛': 'Z', '镇': 'Z', '肇': 'Z', '中': 'Z', '遵': 'Z', '驻': 'Z', '漳': 'Z'
  };
  
  // 检查是否有特殊映射
  if (specialCityMap[firstChar]) {
    return specialCityMap[firstChar];
  }
  
  // 英文字母直接返回大写
  if (/[a-zA-Z]/.test(firstChar)) {
    return firstChar.toUpperCase();
  }
  
  // 数字返回#
  if (/[0-9]/.test(firstChar)) {
    return '#';
  }
  
  // 否则尝试根据Unicode编码确定大致范围
  // 这是一个简化的实现，实际应用可能需要更完善的拼音库
  return '#';
};

// 按行政级别分组的结果
const groupedResults = computed(() => {
  const groups = {
    province: [],
    city: [],
    district: []
  };
  
  searchResults.value.forEach(item => {
    if (item.level && groups[item.level]) {
      groups[item.level].push(item);
    } else if (item.level === 'street' || item.level === 'township') {
      // 将街道、乡镇级别归入区县组
      groups.district.push(item);
    } else {
      // 默认归入城市组
      groups.city.push(item);
    }
  });
  
  return groups;
});

// 组件挂载时加载数据
onMounted(() => {
  setScrollViewHeight();
  loadCityData();
  getCurrentLocation();
});
</script>

<style lang="scss" scoped>
// 颜色变量
$background-color: #f5f5f5;
$card-background: #ffffff;
$text-primary: #333333;
$text-secondary: #666666;
$border-color: #e0e0e0;
$accent-color: #42c8b9;
$active-color: #42c8b9;
$highlight-color: #ff7f00;

.city-select {
  position: relative;
  height: 100vh;
  background-color: $background-color;
  
  // 顶部标签页
  .tabs-container {
    display: flex;
    background-color: $card-background;
    border-bottom: 1px solid $border-color;
    
    .tab {
      flex: 1;
      text-align: center;
      padding: 15px 0;
      font-size: 14px;
      color: $text-secondary;
      
      &.active {
        color: $text-primary;
        font-weight: bold;
        position: relative;
        
        &:after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 25%;
          width: 50%;
          height: 2px;
          background-color: $accent-color;
        }
      }
    }
  }
  
  // 搜索框
  .search-container {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    background-color: $card-background;
    
    .back-btn {
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      font-size: 20px;
      color: $text-secondary;
    }
    
    .search-box {
      flex: 1;
      display: flex;
      align-items: center;
      background-color: $background-color;
      border-radius: 30px;
      padding: 8px 15px;
      
      .search-icon {
        font-size: 16px;
        color: $text-secondary;
        margin-right: 10px;
      }
      
      .search-input {
        flex: 1;
        height: 24px;
        font-size: 14px;
        color: $text-primary;
        &::placeholder {
          color: $text-secondary;
        }
      }
      
      .clear-icon {
        width: 20px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: $text-secondary;
        font-size: 16px;
      }
    }
  }
  
  // 城市列表容器
  .cities-container {
    background-color: $background-color;
    
    // 区块
    .section {
      margin-bottom: 10px;
      
      .section-title {
        font-size: 14px;
        color: $text-secondary;
        padding: 15px 15px 10px;
      }
      
      // 历史城市
      .history-cities {
        display: flex;
        flex-wrap: wrap;
        padding: 0 10px;
        
        .history-city {
          display: inline-flex;
          align-items: center;
          background-color: $card-background;
          border-radius: 20px;
          padding: 8px 15px;
          margin: 0 5px 10px;
          
          .location-icon {
            font-size: 16px;
            margin-right: 5px;
          }
          
          .city-name {
            font-size: 14px;
            color: $text-primary;
          }
        }
      }
      
      // 相关区县
      .related-districts {
        display: flex;
        flex-wrap: wrap;
        padding: 0 10px;
        
        .district-item {
          width: calc(33.33% - 10px);
          margin: 0 5px 10px;
          background-color: $card-background;
          border-radius: 5px;
          padding: 10px 0;
          text-align: center;
          font-size: 14px;
          color: $text-primary;
        }
      }
      
      // 热门城市
      .hot-cities {
        display: flex;
        flex-wrap: wrap;
        padding: 0 10px;
        
        .hot-city {
          width: calc(25% - 10px);
          margin: 0 5px 10px;
          background-color: $card-background;
          border-radius: 5px;
          padding: 10px 0;
          text-align: center;
          font-size: 14px;
          color: $text-primary;
          
          &.active {
            background-color: $active-color;
            color: white;
          }
        }
      }
    }
    
    // 字母分组
    .letter-section {
      margin-bottom: 5px;
      
      .letter-title {
        font-size: 14px;
        color: $text-primary;
        padding: 8px 15px;
        background-color: $background-color;
        font-weight: bold;
      }
      
      .letter-cities {
        background-color: $card-background;
        
        .city-item {
          padding: 15px;
          font-size: 14px;
          color: $text-primary;
          border-bottom: 1px solid $border-color;
          
          &:last-child {
            border-bottom: none;
          }
        }
      }
    }
    
    // 搜索结果
    .search-results {
      background-color: $card-background;
      
      // 搜索结果分组
      .result-group {
        margin-bottom: 15px;
        
        .group-title {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: 10px;
          padding: 0 15px;
        }
        
        .search-result-item {
          padding: 12px 15px;
          font-size: 14px;
          color: $text-primary;
          border-bottom: 1px solid $border-color;
          display: flex;
          align-items: center;
          
          &:last-child {
            border-bottom: none;
          }
          
          .province-text {
            color: $text-secondary;
            margin-left: 2px;
          }
          
          &.province-item {
            font-weight: 500;
            background-color: rgba($accent-color, 0.05);
          }
          
          &.city-item {
            // 默认样式
          }
          
          &.district-item {
            font-size: 13px;
            color: $text-secondary;
          }
        }
      }
    }
    
    // 无搜索结果提示
    .no-results {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30px 0;
      
      .no-results-text {
        font-size: 14px;
        color: $text-secondary;
        margin-bottom: 10px;
      }
      
      .search-tip {
        font-size: 12px;
        color: $text-secondary;
        opacity: 0.8;
      }
    }
    
    // 加载和错误状态
    .loading-state, .error-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 30px 0;
      
      .loading-text, .error-text {
        font-size: 14px;
        color: $text-secondary;
        margin-bottom: 15px;
      }
      
      .retry-btn {
        padding: 8px 16px;
        background-color: $accent-color;
        color: white;
        border-radius: 5px;
        font-size: 14px;
      }
    }
  }
  
  // 字母索引栏
  .alphabet-index {
    position: fixed;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: transparent;
    
    .letter {
      padding: 2px 0;
      font-size: 12px;
      color: $text-secondary;
      
      &.active {
        color: $accent-color;
        font-weight: bold;
      }
    }
  }
}
</style>
